package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request) {
        //  创建map 集合
        HashMap<String, Object> map = new HashMap<>();
        String userId = AuthContextHolder.getUserId(request);
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.valueOf(userId));
        List<OrderDetail> detailArrayList = new ArrayList<>();
        AtomicInteger atomicInteger = new AtomicInteger();
        if (!CollectionUtils.isEmpty(cartCheckedList)) {
            detailArrayList = cartCheckedList.stream().map(cartInfo -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setOrderPrice(cartInfo.getSkuPrice());
                atomicInteger.addAndGet(cartInfo.getSkuNum());
                return orderDetail;
            }).collect(Collectors.toList());
            map.put("detailArrayList", detailArrayList);
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();
        map.put("totalAmount", orderInfo.getTotalAmount());
        map.put("totalNum", atomicInteger);
        String tradeNo = orderService.getTradeCode(userId);
        map.put("tradeNo", tradeNo);
        return Result.ok(map);
    }

    /**
     * 提交订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        String tradeNo = request.getParameter("tradeNo");

        //  单线程操作，多线程就可能会出现误删锁的问题！lua 脚本
        //        Boolean result = this.orderService.checkTradeNo(userId, tradeNo);
        //        if (!result){
        //            //  给他提示信息；
        //            return Result.fail().message("不能重复提交");
        //        }
        //        //  删除流水号
        //        this.orderService.delTradeNo(userId);
        //生成lua脚本
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        String tradeKey = "user:" + userId + ":tradecode";
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), tradeNo);
        if (result == 0) {
            return Result.fail().message("请勿重复提交");
        }

        //  创建多线程集合对象
        List<CompletableFuture> completableFutureArrayList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        //判断库存是否充足
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)) {
            for (OrderDetail orderDetail : orderDetailList) {
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    boolean exist = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!exist) {
                        //return Result.fail().message(orderDetail.getSkuId() + "库存不足");
                        errorList.add(orderDetail.getSkuId() + "库存不足");
                    }
                },threadPoolExecutor);
                completableFutureArrayList.add(stockCompletableFuture);

                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //判断价格是否有变动
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //获取缓存key
                        String redisKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
                        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(redisKey, orderDetail.getSkuId());
                        cartInfo.setSkuPrice(skuPrice);
                        redisTemplate.opsForHash().put(redisKey, orderDetail.getSkuId(), cartInfo);
                        String msg = orderPrice.compareTo(skuPrice) == 1 ? "降价" : "涨价";
                        BigDecimal price = orderPrice.subtract(skuPrice).abs();
                        errorList.add(orderDetail.getSkuId() + "价格有变动" + msg + price + "元");
                    }
                },threadPoolExecutor);
                completableFutureArrayList.add(priceCompletableFuture);

            }
        }
        CompletableFuture.allOf(completableFutureArrayList.toArray(new CompletableFuture[completableFutureArrayList.size()])).join();
        if (errorList.size() > 0) {
            return Result.fail().message(StringUtil.join(errorList, ","));
        }
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

    @GetMapping("/auth/{page}/{limit}")
    public Result getOrder(@PathVariable Long page,
                           @PathVariable Long limit,
                           HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String orderStatus = request.getParameter("orderStatus");
        Page<OrderInfo> cartInfoPage = new Page<>(page, limit);
        IPage<OrderInfo> orderInfoList = orderService.getOrder(cartInfoPage, userId, orderStatus);
        return Result.ok(orderInfoList);
    }

    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId) {
        return orderService.getOrderInfo(orderId);
    }

    @PostMapping("/orderSplit")
    public List<Map<String, Object>> orderSplit(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");
        List<OrderInfo> orderInfoList = orderService.spilt(orderId, wareSkuMap);
        List<Map<String, Object>> mapList = orderInfoList.stream().map(orderInfo -> {
            Map<String, Object> map = orderService.initWareOrder(orderInfo);
            return map;
        }).collect(Collectors.toList());
        return mapList;
    }

    /**
     * 秒杀提交订单，秒杀订单不需要做前置判断，直接下单
     * @param orderInfo
     * @return
     */
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return orderId;
    }
}














